package com.thememaker.lockstyle;

import com.alibaba.fastjson.JSONObject;
import com.thememake.entity.ThemeFileInfo;
import com.thememake.util.FileUtils;
import com.thememake.util.HanYuUtils;
import com.thememake.util.LogUtils;
import com.thememake.util.image.changesize.ImageChangeSizeUtils;
import com.thememake.util.psd.model.Layer;
import com.thememake.util.psd.model.Psd;
import com.thememake.util.psd.parser.layer.LayerParser;
import com.thememake.util.psd.parser.layer.LayerType;
import com.thememake.util.psd.parser.layer.additional.LayerTypeToolHandler;
import com.thememake.util.psd.parser.layer.additional.LayerTypeToolParser;
import com.thememake.util.psd.parser.layer.additional.Matrix;
import com.thememake.util.psd.parser.object.PsdDescriptor;
import com.thememake.util.xml.fontcolor.ReadXmlUtils;
import com.thememaker.lockstyle.bean.Lockscreen;
import com.thememaker.lockstyle.bean.Var;
import com.thememaker.lockstyle.bean.animation.*;
import com.thememaker.lockstyle.bean.command.*;
import com.thememaker.lockstyle.bean.ui.BaseView;
import com.thememaker.lockstyle.bean.ui.Image;
import com.thememaker.lockstyle.bean.ui.Slider;
import com.thememaker.lockstyle.bean.ui.Unlocker;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.w3c.dom.Document;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by jiajun.jiang on 2018/3/4.
 */
public class LockstylePsdUtils {

    private Psd psd;
    private ThemeFileInfo themeFileInfo;
    private String savePath;
    private Lockscreen lockscreen;
    private LinkedHashMap<String, BaseView> linkedHashMap;

    public LockstylePsdUtils(ThemeFileInfo themeFileInfo) {
        this.themeFileInfo = themeFileInfo;
    }

    public void importLockscreen() {
        try {
            lockscreen = new Lockscreen();
            linkedHashMap = new LinkedHashMap<>();
            psd = new Psd(themeFileInfo.getThemeLockscreenPsdFile()) {
                @Override
                protected Layer createLayer(LayerParser parser) {
                    parser.putAdditionalInformationParser(LayerTypeToolParser.TAG, new LayerTypeToolParser(new LayerTypeToolHandler() {

                        @Override
                        public void typeToolTransformParsed(Matrix transform) {
                            System.out.println("transform: " + transform);
                        }

                        @Override
                        public void typeToolDescriptorParsed(int version, PsdDescriptor descriptor) {
                            System.out.println("version: " + version + ", " + descriptor);
                        }
                    }));
                    return super.createLayer(parser);
                }
            };
            Var notificationVar = new Var();
            notificationVar.setName("notification");
            notificationVar.setExpression("1");
            linkedHashMap.put("notification", notificationVar);
            savePath = new File(themeFileInfo.getThemeLockscreenPsdFile().getParentFile(), psd.getName().replace(".psd", "")).getPath();
            if (Files.exists(Paths.get(savePath))) {
                FileUtils.deleteDir(Paths.get(savePath).toFile());
            }
            psd.getLayers().stream().forEach(layer -> {
                System.err.println("layer: " + layer.getName() + " " + layer.getType() + " X: " + layer.getX() + " Y: " + layer.getY());
                //按文件夹裁图
                getLayers(savePath, layer);
            });
            for (String name : linkedHashMap.keySet()) {
                BaseView baseView = linkedHashMap.get(name);
                if (baseView instanceof Image) {
                    Image image = (Image) baseView;
                    if (image.getTime() != null) {
                        int time = Integer.parseInt(image.getTime());
                        if (image.getPositionAnimation() != null && image.getPositionAnimation().getPositionList().size() == 3) {
                            image.getPositionAnimation().getPositionList().get(0).setTime("0");
                            image.getPositionAnimation().getPositionList().get(1).setTime(time / 2 + "");
                            image.getPositionAnimation().getPositionList().get(2).setTime(time + "");
                        }
                        if (image.getAlphaAnimation() != null && image.getAlphaAnimation().getAlphaList().size() == 3) {
                            image.getAlphaAnimation().getAlphaList().get(0).setTime("0");
                            image.getAlphaAnimation().getAlphaList().get(1).setTime(time / 2 + "");
                            image.getAlphaAnimation().getAlphaList().get(2).setTime(time + "");
                        }
                        if (image.getRotationAnimation() != null && image.getRotationAnimation().getRotationList().size() == 3) {
                            image.getRotationAnimation().getRotationList().get(0).setTime("0");
                            image.getRotationAnimation().getRotationList().get(1).setTime(time / 2 + "");
                            image.getRotationAnimation().getRotationList().get(2).setTime(time + "");
                        }
                        if (image.getSizeAnimation() != null && image.getSizeAnimation().getSizeList().size() == 3) {
                            Size size = image.getSizeAnimation().getSizeList().get(0);
                            Size size1 = image.getSizeAnimation().getSizeList().get(1);
                            Size size2 = image.getSizeAnimation().getSizeList().get(2);
                            size.setTime("0");
                            String scale = size.getW();
                            size.setW((int) (Double.parseDouble(scale) * Double.parseDouble(image.getW())) + "");
                            size.setH((int) (Double.parseDouble(scale) * Double.parseDouble(image.getH())) + "");
                            scale = size1.getW();
                            size1.setTime(time / 2 + "");
                            size1.setW((int) (Double.parseDouble(scale) * Double.parseDouble(image.getW())) + "");
                            size1.setH((int) (Double.parseDouble(scale) * Double.parseDouble(image.getH())) + "");
                            scale = size2.getW();
                            size2.setTime(time + "");
                            size2.setW((int) (Double.parseDouble(scale) * Double.parseDouble(image.getW())) + "");
                            size2.setH((int) (Double.parseDouble(scale) * Double.parseDouble(image.getH())) + "");
                        }
                        image.setTime(null);
                    }
                }
                System.err.println(name + " >>> " + JSONObject.toJSONString(baseView));
            }
            lockscreen.setLockScreenViewMap(linkedHashMap);
            Document document = ReadXmlUtils.loadXml(Paths.get(FileUtils.getResFileOfThemeModel(themeFileInfo.getThemeType(), "lockscreen").getPath(), "model", "lockscreen1", "manifest.xml").toString());
            LockstylePaserUtils.saveLockScreenXml(themeFileInfo, document, lockscreen, Paths.get(savePath, "manifest.xml").toFile());
            java.nio.file.Path lockscreenPath = Paths.get(themeFileInfo.getThemeDir().getPath(), themeFileInfo.getThemeType(), ThemeFileInfo.LOCKSTYLE_NAME, "lockscreen");
            FileUtils.deleteDir(lockscreenPath.toFile());
            FileUtils.copy(savePath, lockscreenPath.toString(), null, true, true);
            FileUtils.deleteDir(Paths.get(savePath).toFile());
        } catch (Exception e) {
            LogUtils.getLogger().error(e);
            e.printStackTrace();
        }
    }

    /***
     * 按文件夹层级裁图
     * @param layerParentPath
     * @param layer
     */
    private void getLayers(String layerParentPath, Layer layer) {
        if (layer != null) {
//            System.out.println(layerParentPath + ">>getLayers>>layer: " + layer.getName() + " " + layer.getType());
            BufferedImage image = layer.getImage();
            if (!layer.getType().toString().equals(LayerType.FOLDER.toString())
                    && image != null
                    && !layerParentPath.contains("位置")) {
                System.err.println(layerParentPath + ">>getLayers>>layer: " + layer.getName() + " " + layer.getType() + " x:" + layer.getX() + "  y：" + layer.getY());
                try {
                    if (layer.getName().equals("wallpaper")) {
                        File toFile = new File(layerParentPath, layer.getName() + ".jpg");
                        toFile.getParentFile().mkdirs();
                        System.err.println("缩小背景");
                        ImageIO.write(image, "jpg", toFile);
                        Thumbnails.of(toFile)
                                .sourceRegion(Positions.CENTER, 1080, 1920)
                                .size(1080, 1920)
                                .keepAspectRatio(false)
                                .toFile(new File(toFile.getPath().replace(layer.getName(), "default_lock_wallpaper")));
                        toFile.delete();
                        Image image1 = new Image();
                        image1.setSrc("default_lock_wallpaper.jpg");
                        image1.setX("0");
                        image1.setY("0");
                        linkedHashMap.put("default_lock_wallpaper", image1);
                    } else {
                        saveImage(layer, image, layerParentPath);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                saveImageXml(null, layer);
            }
            layerParentPath = layerParentPath + File.separator + layer.getName();
            String finalLayerParentPath = layerParentPath;
            layer.getLayers().stream().forEach(layer1 -> getLayers(finalLayerParentPath, layer1));
        }
    }

    public void saveImageXml(String srcValue, Layer layer) {
        if (!layer.getType().toString().equals(LayerType.FOLDER.toString())) {
            Image image = null;
            switch (layer.getName()) {
                case "小时1":
                    image = initSaveImage(layer.getName(), "time/time.png", layer);
                    image.setSrcid("ifelse(#time_format,#hour24/10,#hour12/10)");
                    break;
                case "小时2":
                    image = initSaveImage(layer.getName(), "time/time.png", layer);
                    image.setSrcid("ifelse(#time_format,#hour24%10,#hour12%10)");
                    break;
                case "点":
                    image = initSaveImage(layer.getName(), "time/time_dot.png", layer);
                    break;
                case "分钟1":
                    image = initSaveImage(layer.getName(), "time/time.png", layer);
                    image.setSrcid("#minute/10");
                    break;
                case "分钟2":
                    image = initSaveImage(layer.getName(), "time/time.png", layer);
                    image.setSrcid("#minute%10");
                    break;
                case "AM":
                    image = initSaveImage(layer.getName(), "time/a.png", layer);
                    image.setSrcid("#ampm");
                    image.setVisibility("0");
                    break;
                case "年份1":
                    image = initSaveImage(layer.getName(), "date/date.png", layer);
                    image.setSrcid("#year/1000");
                    break;
                case "年份2":
                    image = initSaveImage(layer.getName(), "date/date.png", layer);
                    image.setSrcid("(#year%1000)/100");
                    break;
                case "年份3":
                    image = initSaveImage(layer.getName(), "date/date.png", layer);
                    image.setSrcid("(#year%100)/10");
                    break;

                case "年份4":
                    image = initSaveImage(layer.getName(), "date/date.png", layer);
                    image.setSrcid("#year%10");
                    break;
                case "符号":
                    image = initSaveImage(layer.getName(), "date/date_dot.png", layer);
                    break;
                case "月份1":
                    image = initSaveImage(layer.getName(), "date/date.png", layer);
                    image.setSrcid("(#month+1)/10");
                    break;
                case "月份2":
                    image = initSaveImage(layer.getName(), "date/date.png", layer);
                    image.setSrcid("(#month+1)%10");
                    break;
                case "符号2":
                    image = initSaveImage(layer.getName(), "date/date_dot.png", layer);
                    break;
                case "日期1":
                    image = initSaveImage(layer.getName(), "date/date.png", layer);
                    image.setSrcid("#date/10");
                    break;
                case "日期2":
                    image = initSaveImage(layer.getName(), "date/date.png", layer);
                    image.setSrcid("#date%10");
                    break;
                case "星期":
                    image = initSaveImage(layer.getName(), "week/week.png", layer);
                    image.setSrcid("#day_of_week");
                    break;
                default:
                    image = initSaveImage(layer.getName(), srcValue, layer);
                    break;
            }
            linkedHashMap.put(layer.getName(), image);
        }
    }


    private boolean saveImage(Layer layer, BufferedImage image, String layerParentPath) {
        System.err.println("saveImage >>> " + layer.getName() + "width : " + layer.getWidth() + "  height:" + layer.getHeight());
        if (layerParentPath.contains("动画")) {
            if (layerParentPath.contains("线性动画")) {
                saveLinearAnim(layer, image, layerParentPath);
            } else {
                saveFrameAnim(layer, image, layerParentPath);
            }
        } else if (layerParentPath.contains("解锁")) {
            if (layerParentPath.contains("任意滑解锁")) {
                saveArbitrarilyUnlocker(layer, image, layerParentPath);
            } else {
                saveUnlocker(layer, image, layerParentPath);
            }
        } else if (layerParentPath.contains("密码")) {
            savePassWord(layer, image, layerParentPath);
        } else if (layerParentPath.contains("功能-")) {
            saveFunction(layer, image, layerParentPath);
        } else {
            if (!layer.getName().equals("背景")) {
                saveIcon(image, new File(initSavePath(layerParentPath), initSaveName(layer.getName()) + ".png"), layer.getWidth(), layer.getHeight());
            }
        }
        return true;
    }

    public String initSaveName(String name) {
        String newName = name;
        if (newName.contains("星期日")) {
            newName = "week_1";
        }
        if (newName.contains("星期一")) {
            newName = "week_2";
        }
        if (newName.contains("星期二")) {
            newName = "week_3";
        }
        if (newName.contains("星期三")) {
            newName = "week_4";
        }
        if (newName.contains("星期四")) {
            newName = "week_5";
        }
        if (newName.contains("星期五")) {
            newName = "week_6";
        }
        if (newName.contains("星期六")) {
            newName = "week_7";
        }
        if (newName.contains("AM")) {
            newName = "a_0";
        }
        if (newName.contains("PM")) {
            newName = "a_1";
        }
        return newName;
    }

    public String initSavePath(String layerParentPath) {
        String path = layerParentPath;
        if (path.contains("时间\\时间")) {
            path = layerParentPath.replace("时间\\时间", "time");
        }
        if (path.contains("日期\\日期")) {
            path = layerParentPath.replace("日期\\日期", "date");
        }
        if (path.contains("日期\\星期")) {
            path = layerParentPath.replace("日期\\星期", "week");
        }
        return path;
    }

    private void saveFunction(Layer layer, BufferedImage image, String layerParentPath) {
        String key = layerParentPath.replace(savePath, "");
        System.err.println("saveUnlocker >>> " + key);
        String srcValue = key.replace(File.separator + "功能-", "") + File.separator + layer.getName() + ".png";
        srcValue = new HanYuUtils().getStringPinYin(srcValue).replace(File.separator, "/");
        BaseView baseView = linkedHashMap.get(key);
        String sliderName = "slider" + new HanYuUtils().getStringPinYin(Paths.get(layerParentPath).getFileName().toString());
        Slider slider = new Slider();
        if (baseView != null) {
            slider = (Slider) baseView;
        } else {
            slider.setAlwaysShow("true");
            slider.setBounceAccelation("150");
            slider.setBounceInitSpeed("1500");
            if (key.contains("相机")) {
                sliderName = "sliderCaramel";
            } else if (key.contains("电话")) {
                sliderName = "sliderPhone";
            }
            slider.setName(sliderName);
        }
        if (layer.getName().contains("图片")) {
            if (key.contains("相机")) {
                srcValue = "caramel.png";
            } else if (key.contains("电话")) {
                srcValue = "phone.png";
            }
            key = key + File.separator + layer.toString();
            Image image1 = new Image();
            image1.setSrc(srcValue);
            image1.setX(layer.getX() + "+#" + slider.getName() + ".move_x");
            image1.setY(layer.getY() + "+#" + slider.getName() + ".move_y");
            linkedHashMap.put(key, image1);
            saveIcon(image, new File(savePath, srcValue), layer.getWidth(), layer.getHeight());
        } else {
            if (layer.getName().equals("startpoint")) {
                StartPoint startPoint = new StartPoint(layer.getX() + "", layer.getY() + "", layer.getWidth() + "", layer.getHeight() + "");
                EndPoint endPoint = slider.getEndPoint();
                if (endPoint != null) {
                    List<Position> pathList = new ArrayList<>();
                    Path path = endPoint.getPath();
                    if (path != null) {
                        pathList = path.getPositionList();
                    } else {
                        path = new Path(layer.getX() + "", layer.getY() + "", layer.getWidth() + "", layer.getHeight() + "");
                    }
                    Position position = new Position();
                    path.setX(String.valueOf(0));
                    path.setY(String.valueOf(0));
                    pathList.add(position);
                    Position position1 = new Position();
                    position1.setX(String.valueOf(Integer.parseInt(endPoint.getX()) - layer.getX()));
                    position1.setY(String.valueOf(Integer.parseInt(endPoint.getY()) - layer.getY()));
                    pathList.add(position1);
                    path.setPositionList(pathList);
                    endPoint.setPath(path);
                    slider.setEndPoint(endPoint);
                }
                slider.setStartPoint(startPoint);
                ReachedState reachedState = new ReachedState();
                Trigger trigger = new Trigger();
                if (key.contains("相机")) {
                    IntentCommand intentCommand = new IntentCommand("android.intent.action.MAIN", "com.android.camera", "com.android.camera.CameraActivity");
                    LinkedHashMap<String, BaseCommand> linkedHashMapBaseCommand = new LinkedHashMap<>();
                    linkedHashMapBaseCommand.put("psd_IntentCommand_camera", intentCommand);
                    trigger.setCommandMap(linkedHashMapBaseCommand);
                } else if (key.contains("电话")) {
                    IntentCommand intentCommand = new IntentCommand("android.intent.action.MAIN", "com.android.dialer", "com.android.dialer.TwelveKeyDialer");
                    LinkedHashMap<String, BaseCommand> linkedHashMapBaseCommand = new LinkedHashMap<>();
                    linkedHashMapBaseCommand.put("psd_IntentCommand_dialer", intentCommand);
                    trigger.setCommandMap(linkedHashMapBaseCommand);
                }
                ExternCommand externCommand = new ExternCommand();
                externCommand.setCommand("unlock");
                LinkedHashMap<String, BaseCommand> linkedHashMapBaseCommand = new LinkedHashMap<>();
                linkedHashMapBaseCommand.put("psd_ExternCommand_unlock", externCommand);
                trigger.setCommandMap(linkedHashMapBaseCommand);
                reachedState.setTrigger(trigger);
                startPoint.setReachedState(reachedState);
                linkedHashMap.put(key, slider);
            } else if (layer.getName().equals("endpoint")) {
                EndPoint endPoint = new EndPoint(layer.getX() + "", layer.getY() + "", layer.getWidth() + "", layer.getHeight() + "");
                StartPoint startPoint = slider.getStartPoint();
                if (startPoint != null) {
                    List<Position> pathList = new ArrayList<>();
                    Path path = endPoint.getPath();
                    if (path != null) {
                        pathList = path.getPositionList();
                    } else {
                        path = new Path(startPoint.getX(), startPoint.getY(), startPoint.getW(), startPoint.getH());
                    }
                    Position position = new Position();
                    position.setX(String.valueOf(0));
                    position.setY(String.valueOf(0));
                    Position position1 = new Position();
                    position1.setX(String.valueOf(layer.getX() - Integer.parseInt(startPoint.getX())));
                    position1.setY(String.valueOf(layer.getY() - Integer.parseInt(startPoint.getY())));
                    pathList.add(position);
                    pathList.add(position1);
                    path.setPositionList(pathList);
                    endPoint.setPath(path);
                }
                slider.setEndPoint(endPoint);
                linkedHashMap.put(key, slider);
            } else {
                key = key + File.separator + layer.toString();
                Image image1 = initSaveImage(key, srcValue, layer);
                image1.setX(image1.getX() + "+#" + sliderName + ".move_x");
                image1.setY(image1.getY() + "+#" + sliderName + ".move_y");
                linkedHashMap.put(key, image1);
                saveIcon(image, new File(savePath, srcValue), layer.getWidth(), layer.getHeight());
            }
        }
    }

    private void saveArbitrarilyUnlocker(Layer layer, BufferedImage image, String layerParentPath) {
        String key = layerParentPath.replace(savePath, "");
        System.err.println("saveUnlocker >>> " + key);
        String srcValue = key.replace(File.separator + "任意滑解锁", "unlock") + File.separator + layer.getName() + ".png";
        srcValue = new HanYuUtils().getStringPinYin(srcValue).replace(File.separator, "/");
        System.err.println("srcValue  >>> " + srcValue);

        Var unlock_dist = new Var();
        unlock_dist.setExpression("300");
        unlock_dist.setName("unlock_dist");
        unlock_dist.setConstString("true");
        Var move_dx = new Var();
        move_dx.setExpression("(#touch_x-#touch_begin_x)");
        move_dx.setName("move_dx");
        move_dx.setConstString("false");
        Var move_dy = new Var();
        move_dy.setExpression("(#touch_y-#touch_begin_y)");
        move_dy.setName("move_dy");
        move_dy.setConstString("false");
        Var move_radius = new Var();
        move_radius.setExpression("sqrt(#move_dx*#move_dx+#move_dy*#move_dy)");
        move_radius.setName("move_radius");
        move_radius.setConstString("false");
        linkedHashMap.put("unlock_dist", unlock_dist);
        linkedHashMap.put("move_dx", move_dx);
        linkedHashMap.put("move_dy", move_dy);
        linkedHashMap.put("move_radius", move_radius);

        Unlocker unlocker = new Unlocker();
        unlocker.setName("unlocker");
        unlocker.setAlwaysShow("true");
        StartPoint startPoint = new StartPoint("#touch_begin_x", "#touch_begin_y", "1", "1");
        EndPoint endPoint = new EndPoint("ifelse(ge(#move_radius,#unlock_dist),#touch_x,-1)", "ifelse(ge(#move_radius,#unlock_dist),#touch_y,-1)", "1", "1");
        unlocker.setStartPoint(startPoint);
        unlocker.setEndPoint(endPoint);
        linkedHashMap.put("unlocker", unlocker);

        key = key + File.separator + layer.toString();
        Image image1 = initSaveImage(key, srcValue, layer);
        image1.setX(image1.getX() + "");
        image1.setY(image1.getY() + "");
        linkedHashMap.put(key, image1);
        saveIcon(image, new File(savePath, srcValue), layer.getWidth(), layer.getHeight());
    }

    private void saveUnlocker(Layer layer, BufferedImage image, String layerParentPath) {
        String key = layerParentPath.replace(savePath, "");
        System.err.println("saveUnlocker >>> " + key);
        String srcValue = key.replace(File.separator + "解锁序列帧", "").replace(File.separator + "解锁", "unlock") + File.separator + layer.getName() + ".png";
        srcValue = new HanYuUtils().getStringPinYin(srcValue).replace(File.separator, "/");
        System.err.println("srcValue  >>> " + srcValue);
        if (key.contains("解锁序列帧")) {
            saveSourceAnimationImage(key, srcValue, layer);
            saveIcon(image, new File(savePath, srcValue), layer.getWidth(), layer.getHeight());
        } else {
            BaseView baseView = linkedHashMap.get(key);
            Unlocker unlocker = new Unlocker();
            if (baseView != null) {
                unlocker = (Unlocker) baseView;
            } else {
                unlocker.setAlwaysShow("true");
                unlocker.setBounceAccelation("150");
                unlocker.setBounceInitSpeed("1500");
                unlocker.setName("unlocker");
            }
            if (layer.getName().equals("startpoint")) {
                StartPoint startPoint = new StartPoint(layer.getX() + "", layer.getY() + "", layer.getWidth() + "", layer.getHeight() + "");
                EndPoint endPoint = unlocker.getEndPoint();
                if (endPoint != null) {
                    List<Position> pathList = new ArrayList<>();
                    Path path = endPoint.getPath();
                    if (path != null) {
                        pathList = path.getPositionList();
                    } else {
                        path = new Path(layer.getX() + "", layer.getY() + "", layer.getWidth() + "", layer.getHeight() + "");
                    }
                    Position position = new Position();
                    path.setX(String.valueOf(0));
                    path.setY(String.valueOf(0));
                    pathList.add(position);
                    Position position1 = new Position();
                    position1.setX(String.valueOf(Integer.parseInt(endPoint.getX()) - layer.getX()));
                    position1.setY(String.valueOf(Integer.parseInt(endPoint.getY()) - layer.getY()));
                    pathList.add(position1);
                    path.setPositionList(pathList);
                    endPoint.setPath(path);
                    unlocker.setEndPoint(endPoint);
                }
                unlocker.setStartPoint(startPoint);
                linkedHashMap.put(key, unlocker);
            } else if (layer.getName().equals("endpoint")) {
                EndPoint endPoint = new EndPoint(layer.getX() + "", layer.getY() + "", layer.getWidth() + "", layer.getHeight() + "");
                StartPoint startPoint = unlocker.getStartPoint();
                if (startPoint != null) {
                    List<Position> pathList = new ArrayList<>();
                    Path path = endPoint.getPath();
                    if (path != null) {
                        pathList = path.getPositionList();
                    } else {
                        path = new Path(startPoint.getX(), startPoint.getY(), startPoint.getW(), startPoint.getH());
                    }
                    Position position = new Position();
                    position.setX(String.valueOf(0));
                    position.setY(String.valueOf(0));
                    Position position1 = new Position();
                    position1.setX(String.valueOf(layer.getX() - Integer.parseInt(startPoint.getX())));
                    position1.setY(String.valueOf(layer.getY() - Integer.parseInt(startPoint.getY())));
                    pathList.add(position);
                    pathList.add(position1);
                    path.setPositionList(pathList);
                    endPoint.setPath(path);
                    unlocker.setEndPoint(endPoint);
                }
                unlocker.setEndPoint(endPoint);
                linkedHashMap.put(key, unlocker);
            } else {
                key = key + File.separator + layer.toString();
                Image image1 = initSaveImage(key, srcValue, layer);
                image1.setX("#unlocker.move_x+" + image1.getX());
                image1.setY("#unlocker.move_y+" + image1.getY());
                linkedHashMap.put(key, image1);
                saveIcon(image, new File(savePath, srcValue), layer.getWidth(), layer.getHeight());
            }
        }
    }

    private Image initSaveImage(String key, String srcValue, Layer layer) {
        BaseView baseView = linkedHashMap.get(key);
        Image imageView = new Image();
        if (baseView != null) {
            imageView = (Image) baseView;
        }
        imageView.setX(layer.getX() + "");
        imageView.setY(layer.getY() + "");
        imageView.setSrc(srcValue);
        return imageView;
    }

    private void saveSourceAnimationImage(String key, String srcValue, Layer layer) {
        BaseView baseView = linkedHashMap.get(key);
        Image imageView = new Image();
        if (baseView != null) {
            imageView = (Image) baseView;
        } else {
            imageView.setX(layer.getX() + "");
            imageView.setY(layer.getY() + "");
        }
        SourcesAnimation sourcesAnimation = imageView.getSourcesAnimation();
        if (sourcesAnimation == null) {
            sourcesAnimation = new SourcesAnimation();
        }
        List<Source> sourceList = sourcesAnimation.getSourceList();

        if (sourceList == null) {
            sourceList = new ArrayList<>();
            Source source = new Source();
            source.setSrc(srcValue);
            source.setTime("0");
            sourceList.add(source);
            Source source1 = new Source();
            source1.setSrc(srcValue);
            source1.setTime("0");
            sourceList.add(source);
        } else {
            int count = sourceList.size();
            Source source = sourceList.get(count - 1);
            Source source2 = new Source();
            source2.setSrc(source.getSrc());
            source2.setTime(200 * count + "");
            Source source1 = new Source();
            source1.setSrc(srcValue);
            source1.setTime(200 * (count - 1) + "");
            sourceList.set(count - 1, source1);
            sourceList.add(source2);
        }
        sourcesAnimation.setSourceList(sourceList);
        imageView.setSourcesAnimation(sourcesAnimation);
        linkedHashMap.put(key, imageView);
    }


    private void savePassWord(Layer layer, BufferedImage image, String layerParentPath) {
//        String key = layerParentPath.replace(savePath,"");
//        System.err.println("savePassWord >>> " + key);
//        String srcValue = key.replace(File.separator+"密码","mmpad");
//        key = key.replace("正常",layer.getName()).replace("点击",layer.getName());
//        if (layerParentPath.contains(File.separator+"点击")){
//            srcValue = srcValue.replace(File.separator+"点击",File.separator+"btn") + File.separator + layer.getName()+"_p.png";
//        }else if (layerParentPath.contains(File.separator+"正常")){
//            srcValue = srcValue.replace(File.separator+"正常",File.separator+"btn") + File.separator + layer.getName()+".png";
//        }else if (layerParentPath.contains(File.separator+"提示")){
//            srcValue = srcValue.replace(File.separator+"提示",File.separator+"mmts") + File.separator + layer.getName()+".png";
//        }else{
//            srcValue = srcValue + File.separator + layer.getName()+".png";
//        }
//        srcValue = new HanYuUtils().getStringPinYin(srcValue).replace(File.separator,"/");
//        List<BaseView> passwordPoints = passwordView.getPasswordPoint();
//        if (passwordPoints == null){
//            passwordPoints = new ArrayList<>();
//        }
//        if (layerParentPath.contains(File.separator+"提示")){
//            passwordPoints.add(new BaseView(layer.getX()+"",layer.getY()+"",layer.getWidth()+"",layer.getHeight()+"",srcValue));
//            passwordView.setPasswordPoint(passwordPoints);
//        }else if (layerParentPath.contains(File.separator+"正常")){
//            PasswordItem passwordItem = passwordItemMap.get(key);
//            if (passwordItem == null){
//                passwordItem = new PasswordItem();
//            }
//            passwordItem.setNormalView(new BaseView(layer.getX()+"",layer.getY()+"",layer.getWidth()+"",layer.getHeight()+"",srcValue));
//            passwordItemMap.put(key,passwordItem);
//        }else if ( layerParentPath.contains(File.separator+"点击")){
//            PasswordItem passwordItem = passwordItemMap.get(key);
//            if (passwordItem == null){
//                passwordItem = new PasswordItem();
//            }
//            passwordItem.setPressedView(new BaseView(layer.getX()+"",layer.getY()+"",layer.getWidth()+"",layer.getHeight()+"",srcValue));
//            passwordItemMap.put(key,passwordItem);
//        }else {
//            lockScreenXmlUtil.saveImageXml(layer.getX()+"",layer.getY() + "",srcValue);
//        }
//        saveIcon(image,new File(savePath,srcValue),layer.getWidth(),layer.getHeight());
    }

    private void saveFrameAnim(Layer layer, BufferedImage image, String layerParentPath) {
        String key = layerParentPath.replace(savePath, "");
        String srcValue = key.replace(File.separator + "动画", "anim").replace("序列帧", "frame") + File.separator + layer.getName() + ".png";
        srcValue = new HanYuUtils().getStringPinYin(srcValue).replace(File.separator, "/");
        saveSourceAnimationImage(key, srcValue, layer);
        saveIcon(image, new File(savePath, srcValue), layer.getWidth(), layer.getHeight());
    }

    private void saveLinearAnim(Layer layer, BufferedImage image, String layerParentPath) {
        String key = layerParentPath.replace(savePath, "");
        String srcValue = key.replace(File.separator + "动画", "anim").replace("线性动画", "linear") + File.separator + "1.png";
        srcValue = new HanYuUtils().getStringPinYin(srcValue).replace(File.separator, "/");
        BaseView baseView = linkedHashMap.get(key);
        Image imageView = new Image();
        if (baseView != null) {
            imageView = (Image) baseView;
        }
        switch (layer.getName()) {
            case "图片":
                imageView.setSrc(srcValue);
                imageView.setW(layer.getWidth() + "");
                imageView.setH(layer.getHeight() + "");
                imageView.setX(layer.getX() + "");
                imageView.setY(layer.getY() + "");
                saveIcon(image, new File(savePath, srcValue), layer.getWidth(), layer.getHeight());
                break;
            case "起始":
            case "中间":
            case "结束":
                PositionAnimation positionAnimation = imageView.getPositionAnimation();
                if (positionAnimation == null) {
                    positionAnimation = new PositionAnimation();
                }
                List<Position> positionList = positionAnimation.getPositionList();
                if (positionList == null) {
                    positionList = new ArrayList<>();
                }
                Position position = new Position();
                position.setX(layer.getX() + "");
                position.setY(layer.getY() + "");
                positionList.add(position);
                positionAnimation.setPositionList(positionList);
                imageView.setPositionAnimation(positionAnimation);
                break;
            default:
                break;
        }
        String value = layer.getName().substring(layer.getName().indexOf("_") + 1);
        if (layer.getName().contains("alpha")) {
            if (!value.equals("-1")) {
                AlphaAnimation alphaAnimation = imageView.getAlphaAnimation();
                if (alphaAnimation == null) {
                    alphaAnimation = new AlphaAnimation();
                }
                List<Alpha> alphaList = alphaAnimation.getAlphaList();
                if (alphaList == null) {
                    alphaList = new ArrayList<>();
                }
                Alpha alpha = new Alpha();
                alpha.setA((int) (Double.parseDouble(value) * 255 / 100) + "");
                alphaList.add(alpha);
                alphaAnimation.setAlphaList(alphaList);
                imageView.setAlphaAnimation(alphaAnimation);
            }
        }
        if (layer.getName().contains("rotation")) {
            if (!value.equals("-1")) {
                RotationAnimation rotationAnimation = imageView.getRotationAnimation();
                if (rotationAnimation == null) {
                    rotationAnimation = new RotationAnimation();
                }
                List<Rotation> rotationList = rotationAnimation.getRotationList();
                if (rotationList == null) {
                    rotationList = new ArrayList<>();
                }
                Rotation rotation = new Rotation();
                rotation.setAngle(value);
                rotationList.add(rotation);
                rotationAnimation.setRotationList(rotationList);
                imageView.setRotationAnimation(rotationAnimation);
            }
        }
        if (layer.getName().contains("size")) {
            if (!value.equals("-1")) {
                SizeAnimation sizeAnimation = imageView.getSizeAnimation();
                if (sizeAnimation == null) {
                    sizeAnimation = new SizeAnimation();
                }
                List<Size> sizeList = sizeAnimation.getSizeList();
                if (sizeList == null) {
                    sizeList = new ArrayList<>();
                }
                Size size = new Size();
                size.setW(value);
                sizeList.add(size);
                sizeAnimation.setSizeList(sizeList);
                imageView.setSizeAnimation(sizeAnimation);
            }
        }
        if (layer.getName().contains("time")) {
            imageView.setTime(value);
        }
        linkedHashMap.put(key, imageView);
    }

    private void saveIcon(BufferedImage image, File toFile, int imageWidth, int imageHeight) {
        try {
            toFile.mkdirs();
            int width = image.getWidth();
            int height = image.getHeight();
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    if (i == 0 || i == width - 1 || j == 0 || j == height - 1) {
                        image.setRGB(i, j, java.awt.Color.TRANSLUCENT);
                    }
                }
            }
            ImageIO.write(image, "png", toFile);
            ImageChangeSizeUtils.ImageChangeSize(toFile.getPath(), toFile.getPath(), imageWidth, imageHeight);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
